<?php
/*************************************************

IM融云即时通讯 - the 
Author: WangHuabin <17-11-20>

*************************************************/
namespace Home\Controller;
use Think\Controller;
class ImController extends CommonController {
        private static $APP_KEY = 'vnroth0krmivo';
        private static $APP_SECRET = 'J71B0l99sEKm';
        private static $JSON_PATH = 'jsonsource/';

        public function __construct() {
            parent::__construct();
            include './App/Api/rongcloud/rongcloud.php';
        }

        //获取用户token
        public function get_token(){
            $appKey = self::$APP_KEY;
            $appSecret = self::$APP_SECRET;
            $jsonPath = self::$JSON_PATH;
            $RongCloud = new \RongCloud($appKey,$appSecret);
            $userid = $_SESSION['user']['id'];
            $nickname = $_SESSION['user']['nickname'];
            $img = $_SESSION['user']['url_img'];
            $result = $RongCloud->User()->getToken($userid,$nickname,$img);
            $r = json_decode($result,true);
            if($r['code']==200){
                $map['id'] =$r['userId'];
                $data['rong_token'] = $r['token'];
                $res = D('User')->edit($map,$data);
                if($res){
                    $data = array('err'=>0,'msg'=>"token获取成功！",'token'=>$r['token']);
                }else{
                      $data = array('err'=>1,'msg'=>"token更新失败！");
                }
            }else{
                  $data = array('err'=>2,'msg'=>"token获取失败！");
            }
            return json_encode($data);
       
        }

        //刷新用户信息
        public function refresh_msg(){
            $appKey = self::$APP_KEY;
            $appSecret = self::$APP_SECRET;
            $jsonPath = self::$JSON_PATH;
            $RongCloud = new \RongCloud($appKey,$appSecret);
            $userid = $_SESSION['user']['id'];
            $nickname = $_SESSION['user']['nickname'];
            $img = $_SESSION['user']['url_img'];
            $result = $RongCloud->user()->refresh($userid,$nickname,$img);
            echo "refresh    ";
            print_r($result);;
        }

        //检查用户在线状态
        public function checkonline(){
            $appKey = self::$APP_KEY;
            $appSecret = self::$APP_SECRET;
            $jsonPath = self::$JSON_PATH;
            $RongCloud = new \RongCloud($appKey,$appSecret);
            $result = $RongCloud->user()->checkOnline(146);
                echo "checkOnline    ";
                print_r($result);
                echo "\n";
        }
        //发送单聊消息（文本）
        // public function send_msg(){
        //     $appKey = self::$APP_KEY;
        //     $appSecret = self::$APP_SECRET;
        //     $jsonPath = self::$JSON_PATH;
        //     $RongCloud = new \RongCloud($appKey,$appSecret);
        //     $userid = $_SESSION['user']['id'];
        //     $nickname = $_SESSION['user']['nickname'];
        //     $img = $_SESSION['user']['url_img'];
        //     $result = $RongCloud->message()->publishPrivate('146', ["8"], 'RC:TxtMsg',"   {\"content\":\"sbsbsbsbsbsbsbsbsb\",\"extra\":\"helloExtra\"}", 'thisisapush', '{\"pushData\":\"hello\"}', '4', '0', '0', '0', '0');
        //     echo "publishPrivate    ";
        //     print_r($result);
        //     echo "\n";
        // }
        
        /*
        *创建群组方法（创建群组，并将用户加入该群组，用户将可以收到该群的消息，同一用户最多可加入 500 个群，每个群最大至 3000 人，App 内的群组数量没有限制.注：其实本方法是加入群组方法 /group/join 的别名。）
         */
         
        public function create_group($userId=8,$groupId=1,$groupName='王大爷的群',$platform_id){
                $appKey = self::$APP_KEY;
                $appSecret = self::$APP_SECRET;
                $jsonPath = self::$JSON_PATH;
                $RongCloud = new \RongCloud($appKey,$appSecret);
                $result = $RongCloud->group()->create($userId,$groupId,$groupName);
                $r = json_decode($result,true);
                if($r['code']==200){
                    //进入群组
                    //创建群组(查询群组)
                    $map['groupid'] = $groupId;
                    $g_info = M('ImGroup')->where($map)->find();

                    if(!$g_info){
                        $data['name'] = $groupName;
                        $data['groupid'] = $groupId;
                        $data['platform_id'] = $platform_id;
                        $data['add_time'] = time();
                        $g_res = M('ImGroup')->data($data)->add();
                        $g_id = $g_res;
                    }else{
                        $g_id = $g_info['groupid'];
                    }
                    if($g_id){
                        $map = array();
                        $map['user_id'] = $userId;
                        $map['group_id'] = $groupId;
                        $g_u = M('ImGroupUser')->where($map)->find();
                        if(!$g_u){
                            $data['user_id'] = $userId;
                            $data['group_id'] = $g_id;
                            $data['add_time'] = time();
                            $g_u = M('ImGroupUser')->data($data)->add();
                        }else{
                            $data = array('err'=>1,'msg'=>"用户已经入群");
                            return json_encode($result);
                        }
                    }
                     $data = array('err'=>0,'msg'=>"成功");
                   
                }else{
                    $data = array('err'=>1,'msg'=>"失败");
                }

                return json_encode($result);
        }

        //查询群成员
          public function query_user($groupId=1){
                $appKey = self::$APP_KEY;
                $appSecret = self::$APP_SECRET;
                $jsonPath = self::$JSON_PATH;
                $RongCloud = new \RongCloud($appKey,$appSecret);
                $result = $RongCloud->group()->queryUser($groupId);
                echo "queryUser";
                print_r($result);
                echo "\n";
        }

        public function firend_list(){
            $appKey = self::$APP_KEY;
            $appSecret = self::$APP_SECRET;
            $jsonPath = self::$JSON_PATH;
            $RongCloud = new \RongCloud($appKey,$appSecret);
            $userid = $_SESSION['user']['id'];
            $nickname = $_SESSION['user']['nickname'];
            $img = $_SESSION['user']['url_img'];
            $token = $this->get_token();
            $token = json_decode($token,true);
            if($token['err']==0){
                $token = $token['token'];
            }

            // 查询好友列表;
            $map['user_id'] =  $userid;
            $firend_list = M('ImFriend')->where($map)->select();
            foreach ($firend_list as $k => $v) {
                $map['id'] = $v['friend_id'];
                
                $user_info = D('User')->get_one($map);
                $firend_list[$k]['user_info']=$user_info;
                $send_id = $user_info['id'];
                $map = array();
                $map['receive_id'] = $userid;
                $map['send_id'] = $send_id;
                $map['is_read'] = 0;
                $firend_list[$k]['is_noread_count'] = M('Chat')->where($map)->count();
                $firend_list[$k]['type'] =1;
            }
            // 查询群组列表;
            $map['user_id'] =  $userid;
            $group_list = M('ImGroupUser')->where($map)->select();
            foreach ($group_list as $k => $v) {
                $map['groupid'] = $v['group_id'];
                $group_info = M('ImGroup')->where($map)->find();
                $group_list[$k]['group_info']=$group_info;
                $send_id = $group_info['id'];
                $map = array();
                $map['group_id'] = $send_id;
                $map['is_read'] = 0;
                $group_list[$k]['is_noread_count'] = 0;
                // $group_list[$k]['is_noread_count'] = M('Chat')->where($map)->count();
                //echo M('Chat')->_sql();
                $group_list[$k]['type'] =2;
            }
            $list = array_merge($group_list,$firend_list);
            return $list;die;
            $this->assign('firend_list',$firend_list);
            $this->assign('rong_token',$token);
            $this->assign('rong_key',$appKey);
            $this->display();
        }

        public function get_user_info(){
            $userid = $_SESSION['user']['id'];
            $map['user_id'] =  $userid;
            $firend_list = M('ImFriend')->where($map)->select();
            foreach ($firend_list as $k => $v) {
                $map['id'] = $v['friend_id'];
                $firend_list[$k]['user_info']=D('User')->get_one($map);
                $arr['userlist'][$k]['id'] =  $firend_list[$k]['user_info']['id'];
                $arr['userlist'][$k]['name'] = $firend_list[$k]['user_info']['nickname'];
                $arr['userlist'][$k]['portraitUri'] = $firend_list[$k]['user_info']['url_img'];
               
            }

            $this->ajaxReturn($arr);
       
        }


        public function test(){
            $appKey = self::$APP_KEY;
            $appSecret = self::$APP_SECRET;
            $jsonPath = self::$JSON_PATH;
            $RongCloud = new \RongCloud($appKey,$appSecret);
            $userid = $_SESSION['user']['id'];
            $nickname = $_SESSION['user']['nickname'];
            $img = $_SESSION['user']['url_img'];
            $token = $this->get_token();
            $token = json_decode($token,true);
            if($token['err']==0){
                $token = $token['token'];
            }

            $this->assign('rong_token',$token);
            $this->assign('rong_key',$appKey);
            $this->display();
        }

        public function online(){
            $r='{"data":[{"id":"8","status":true},{"id":"146","status":true},{"id":"1724","status":true},{"id":"939","status":false}]}';
            echo $r;
        }

        public function talk(){
            $appKey = self::$APP_KEY;
            $appSecret = self::$APP_SECRET;
            $jsonPath = self::$JSON_PATH;
            $RongCloud = new \RongCloud($appKey,$appSecret);
            $to_id = I('get.id');
            $userid = $_SESSION['user']['id'];
            //判断师徒关系
            $map = array();
            $map['user_id'] = $to_id;
            $res_to = D('Recommend')->get_one($map);
    
            $map['user_id'] = $userid;
            $map['recommend_id'] = $res_to['id'];
            $map['status'] = 1;
            $r = D('AdviserFollow')->get_one($map);

            // if(!$r && $_SESSION['user']['role'] == 2){

            //     $map = array();
            //     $map['user_id'] = $userid;
            //     $res = D('Recommend')->get_one($map);
            //     $recommend_id = $res['id'];
            //     $map = array();
            //     $map['recommend_id'] = $recommend_id;
            //     $map['user_id'] = $to_id;
            //     $map['status'] = 1;
            //     $r_f = D('AdviserFollow')->get_one($map);
               
            //     if(!$r_f){
            //         $data = array('err'=>1,'msg'=>"只有师徒能进行私信哦！");
            //         $this->assign('data',$data);
            //         $this->display('Im/msg');
            //         return false;
            //     }
            // }elseif(!$r && $_SESSION['user']['role'] != 2){
            //         $data = array('err'=>1,'msg'=>"只有师徒能进行私信哦！");
            //         $this->assign('data',$data);
            //         $this->display('Im/msg');
            //         return;
            // }
            //判短好友关系
            $map = array();
            $map['_string'] = 'user_id='.$userid.' AND friend_id='.$to_id.' OR user_id='.$to_id.' AND friend_id='.$userid;
            $is_friend = D('ImFriend')->where($map)->find();
            if(!$is_friend){
                $arr['user_id'] = $userid;
                $arr['friend_id'] = $to_id;
                $arr['add_time'] = time();
                D('ImFriend')->data($arr)->add();
            }
            $nickname = $_SESSION['user']['nickname'];
            $img = $_SESSION['user']['url_img'];
            $token = $this->get_token();
            $token = json_decode($token,true);
            if($token['err']==0){
                $token = $token['token'];
            }
            $map = array();
            $map['id'] = $to_id;
            $to_info = D('User')->get_one($map);
            $map['id']  =$_SESSION['user']['id'];
            $owner_info = D('User')->get_one($map);
            $this->assign('to_info',$to_info);
            $this->assign('owner_info',$owner_info);
            $this->assign('rong_token',$token);
            $this->assign('rong_key',$appKey);
            $this->display();
        }



        //添加聊天记录
        public function add_messages(){
            $send_id = I("post.send_uin",0,"int");
            $map['id'] = $send_id;
            $userinfo = D('User')->get_one($map);
           if($userinfo['card_status']!=1){
            $this->ajaxReturn(array("err"=>2,"msg"=>"您还未进行实名认证，该消息发送不成功！"));
           }
            $receive_id = I("post.receive_uin",0,"int");
            $group_id = I("post.group_id","");
            $msg_id = I("post.msg_id","");
            $content = trim($_POST["content"]);
            if(!$send_id || empty($content)){
                $this->ajaxReturn(array("err"=>1,"msg"=>"参数错误"));
            }
            
            $data = array();
            $data["send_id"] = $send_id;
            $data["receive_id"] = $receive_id;
            $data["content"] = $content;        
            $data["messageid"] = $msg_id;        
            $data["group_id"] = $group_id?$group_id:0;      
            $data['add_time']   =   time();
            $row    =   M('chat')->add($data); 
            if($row){
                return true;
            }else{
                return false;
            }
    }
        

    //获取历史聊天记录
        public function get_messages(){ 
            $userid =$_SESSION['user']['id'];
            $is_read = I("post.is_read",0,"int");
            $val = I("post.val",0,"int");
            $id = I("post.id",0,"int");
            $to_id = I("post.to_id",0,"int");
            $num=100;
            if(!$to_id){
                $this->ajaxReturn(array("err"=>1,"msg"=>"参数错误"));
            }
            
            $userid    =   $_SESSION['user']['id'];
            
            $map['send_id']  = array('in', array($userid,$to_id));
            $map['receive_id']  = array('in', array($userid,$to_id));
            
           if($val==1){
                if($id){
                $map['id'] = array('lt',$id);
                }
                $map['is_read'] = array('eq',1);
                $list   =   M('chat')->where($map)->order('add_time desc')->select();
           }else{
               if($id){
                $map['id'] = array('lt',$id);
               }
                $list   =   M('chat')->where($map)->order('add_time desc')->select();
           }
            $map['is_read']  = 0;
            M('chat')->where($map)->setField("is_read",1);
            $this->ajaxReturn($list);
    }

        //获取历史聊天记录
        public function get_group_messages(){
            $group_id = I("post.group_id");
            $num = I("post.num",20,"int");
            $id = I("post.id",0,"int");
            if(empty($num)){
                $num = 20;
            }
            if(!$group_id){
                $this->ajaxReturn(array("err"=>1,"msg"=>"参数错误"));
            }
            if(empty($group_id)){
            return false;
            }

            $uin    =   $_SESSION['user']['id'];
            $map['user_id'] = $uin;
            $map['group_id'] = $group_id;
            $userinfo = D('ImGroupUser')->where($map)->find();
          // print_r($userinfo);
            $map = array();
            $map['add_time']  = array('gt',$userinfo['add_time']);  //聊天记录只展示加入群聊之后的
            
            $map['group_id']    =   $group_id;
            if($id>0){
                $map['id'] =   array('lt',$id);
            }
            $row    =   M('chat')->where($map)->order('add_time desc')->limit($num)->select();
          //echo M('chat')->_sql();die;
            // print_r($tosuer);
            // echo 111;
            foreach ($row as $k => $v) {
                $map['id'] = $v['send_id'];
                $tosuer = D('user')->where($map)->find();
                $row[$k]['portraituri'] = $tosuer['url_img'];
                $row[$k]['name'] = $tosuer['nickname'];
            }
            // print_r($tosuer);
            $this->ajaxReturn($row);


        }

        public function group(){
             $pushid = I("get.pushid");
             $id = I("get.id");

             if($pushid){
                $map['groupid'] = '88'.$pushid;
                $group = M('ImGroup')->where($map)->find();
                if(!$group){
                    $group['groupid']= '88'.$pushid;
                    $group['name']= "群组";
                }
                $res = $this->create_group($userId=$_SESSION['user']['id'],$groupId=$group['groupid'],$groupName=$group['name'],$platform_id=0);

             }else{
                $map['platform_id'] = $id;
                $group = M('ImGroup')->where($map)->find();
                if(!$group){
                    $id = I("get.id");
                    $maps['id'] = $id;
                    $p_info = D('Platform')->get_one($maps);
                    $group['groupid']=$id;
                    $group['name']= $p_info['name']."圈子";
                }
                $res = $this->create_group($userId=$_SESSION['user']['id'],$groupId=$group['groupid'],$groupName=$group['name'],$platform_id=$id);
            }
             $this->assign('group_id',$group['groupid']);
             //查询用户是否在组内
             $map['group_id'] =$group['groupid'];
             $map['user_id'] = $_SESSION['user']['id'];
             $this->get_token();
             $r = M('ImGroupUser')->where($map)->find();

             if($r){
                $group_id = $r['group_id'];
                $map = array();
                $map['groupid'] = $group_id;
                $group_info = M('ImGroup')->where($map)->find();
                $group_name = $group_info['name'];
				if($pushid = $_SESSION['user']['id']){
					$page_title = "正在我的群组内交谈。。";
				}else{
					$page_title = "正在".$group_name."群组内交谈。。";
				}
                
                $map = array();
                $map['id']  =$_SESSION['user']['id'];
                $owner_info = D('User')->get_one($map);
                $this->assign('owner_info',$owner_info);
                $to_info["group_id"] = $group_id;
                $this->assign('to_info',$to_info);
             }else{
                $this->assign('is_no',1);
             }
            $appKey = self::$APP_KEY;
            $appSecret = self::$APP_SECRET;
            
             $this->assign('page_title',$page_title);
             $this->assign('rong_token',$token);
             $this->assign('rong_key',$appKey);
             $this->display();
        }

        public function del_friend(){
            $type = I('post.type');
            $id = I('post.id');
            $map['id'] = $id;
            if($type==2){
               $r =  M('ImGroupUser')->where($map)->delete();
            }else{
               $r =  M('ImFriend')->where($map)->delete();
              // echo  M('ImFriend')->_sql();
            }
            if($r){
                $data = array('err'=>0,'msg'=>"成功！");
            }else{
                $data = array('err'=>'1','msg'=>"失败！");
            }
            $this->ajaxReturn($data);
        }



        //微信图片
        public function wx_js(){
            import("Api.Jssdk");
            $project_id = I("get.project_id",37,"int");
            $Jssdk = new \Jssdk(0,$project_id);
            $SignPackage = $Jssdk->getSignPackage($_SERVER['HTTP_REFERER']);
            $this->assign('SignPackage',$SignPackage);
            $this->display();
        }
    

}